<?php

namespace App\Models;

use App\Models\Mini\FleaGoodsModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class FleaOrder extends Model
{
    use SoftDeletes;

    protected $table = 'flea_order';

    protected $guarded = [];

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'pay_at' => 'datetime:Y-m-d H:i:s'
    ];

    protected $appends = ['state_text'];

    protected function serializeDate(\DateTimeInterface $date)
    {
        return $date->format($this->dateFormat ?: 'Y-m-d H:i:s');
    }


    //用户地址转php数组
    public function getUserAddressAttribute($value)
    {
        return json_decode($value, true);
    }

    //方式
    public function getDealTypeAttribute($value)
    {
        $text = '其他';
        if ($value == 1) {
            $text = '自提';
        } elseif ($value == 2) {
            $text = '面交';
        }

        return $text;
    }

    public function getStateTextAttribute()
    {
        $text = '';

        switch ($this->state) {
            case 1:
                $text = '待付款';
                break;
            case 2:
                $text = '待取货';
                break;
            case 3:
                $text = '待评价';
                break;
            case 4:
                $text = '已完成';
                break;
        }

        return $text;
    }

    /**
     * 关联商品表
     */
    public function goods()
    {
        return $this->hasOne(FleaGoodsModel::class, 'id', 'goods_id');
    }

    /**
     * 关联评论
     */
    public function comment()
    {
        return $this->hasOne(FleaOrderComment::class, 'order_id', 'id');
    }

    //关联卖家用户
    public function user()
    {
        return $this->hasOneThrough(User::class, FleaGoodsModel::class, 'id', 'id', 'goods_id', 'user_id');
    }

    //关联买家用户
    public function byUser()
    {
        return $this->hasOne(User::class, 'id','user_id');
    }


    /**
     * @param $data
     * 参数说明
     * out_trade_no 单号
     * transaction_id 微信的单号
     * time_end  支付时间
     * total_fee 用户支付的金额
     *
     */
    public static function updateOrder($data)
    {
        DB::transaction(function () use ($data) {
            $order = self::query()->where('order_sn', $data['out_trade_no'])->firstOrFail();
            //订单是否没有支付
            if ($order['state'] == 1 && !$order['pay_at']) {
                //订单状态改为已支付
                self::query()->where('order_sn', $data['out_trade_no'])->update([
                    'pay_at' => date('Y-m-d H:i:s', strtotime($data['time_end'])),
                    'state' => 2
                ]);
                //卖家余额增加

                //获取卖家ID
                $user_id = FleaGoodsModel::query()->where('id', $order['goods_id'])->value('user_id');

                //商品状态改为已卖出
                FleaGoodsModel::query()->where('id', $order['goods_id'])->update(['is_sale' => 1]);

                //卖家余额加用户实际支付的余额 修改 用户确认收货结算余额
                //User::query()->where('id', $user_id)->increment('flea_money', ($data['total_fee'] / 100));
            }

        });
    }


    /**
     * @param $where array 条件
     * @param $page
     * @param $limit
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     * 获取订单列表
     */
    public static function adminList($where, $page, $limit)
    {
        $offset = ($page == 1) ? 0 : ($page - 1) * $limit;

        $data = self::query()->with('goods:id,goods_name,goods_images')->where($where)->offset($offset)->limit($limit)->orderByDesc('id')->get();

        $response['data'] = $data;
        $response['count'] = self::query()->where($where)->count();
        $response['pages'] = ceil($response['count'] / $limit);
        return $response;
    }
}
